# -*- coding: utf-8 -*-
import wx
import random


class pyDemin:

    #Initialisation
    def __init__(self,w,h,n):
        self.w=w
        self.h=h
        self.dec=[0]*w*h
        self.grille=[0]*w*h
        self.nbMines=n
        self.mine=[-1]*self.nbMines+[0]*(self.w*self.h-self.nbMines)
        random.shuffle(self.mine)

    #Indique s'il y a 1 mine en (x,y)
    def imine(self,x,y):
        if y<self.h and x<self.w and y>-1 and x>-1:
            if self.mine[self.w*y+x]==-1:
                return 1
            else:
                return 0
        else :
                return 0

    def debut(self,x,y):
        if y<self.h and x<self.w and y>-1 and x>-1:
            while self.mine[y*self.w+x]==-1:
                 random.shuffle(self.mine) 
            self.decouvre(x,y)

        
    def __repr__(self):
        s=''
        for i in range(self.w*self.h):
            s+=str(self.grille[i])+' '
            if (i+1)%self.w==0:
                s+='\n'
        return s
    
    #?
    def triche(self):
        s=''
        for i in range(self.w*self.h):
            s+=str(self.mine[i])+' '
            if (i+1)%self.w==0:
                s+='\n'
        print s

    #Indique le nombre de mines dans le voisinage de (x,y)
    def nbmine(self,x,y):
        if y<self.h and x<self.w and y>-1 and x>-1:
            a=0
            for i in range(3):
                for j in range(3):
                    a+=int(self.imine(x+(i-1),y+(j-1)))
            self.grille[self.w*y+x]=a
            return a

    #Decouvre la case (x,y)
    def decouvre(self,x,y):
        if y<self.h and x<self.w and y>-1 and x>-1:
            if self.dec[y*self.w+x]<1:
                self.dec[y*self.w+x]=1
                if self.mine[y*self.w+x]==-1:
                    print 'perdu'
                else:
                    if int(self.nbmine(x,y))==0:
                        for i in range(3):
                            for j in range(3):
                                self.decouvre(x+(i-1),y+(j-1))
     

    def aamine(self,x,y):
        if y<self.h and x<self.w and y>-1 and x>-1:
            self.dec[y*self.w+x]=-1
        
    def aamineAJ(self,x,y):
        if y<self.h and x<self.w and y>-1 and x>-1:
            self.dec[y*self.w+x]=-2
